package com.fs.web.base.controller;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.EmptyWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.fs.common.baseMapper.IntegralMapper;
import com.fs.common.baseMapper.UserMapper;
import com.fs.common.pojo.Integral;
import com.fs.common.pojo.IntegralOrder;
import com.fs.common.pojo.IntegralProduct;
import com.fs.common.pojo.User;
import com.fs.common.yzMapper.IntegralOrderMapper;
import com.fs.common.yzMapper.IntegralProductMapper;
import com.fs.web.base.enums.CodeEnum;
import com.fs.web.base.utils.ApplicationUtils;
import com.fs.web.base.utils.PageHeper;
import com.fs.web.base.vo.DataGrid;
import com.fs.web.base.vo.JsonResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * \* @author: Mr.Zhou
 * \* @description:积分订单Controller
 * \* @create: 2019-12-18 10:54
 * \
 */

@Controller
@Slf4j
@RequestMapping("/console/integral/order")
public class IntegralOrderController {

    @Autowired
    IntegralOrderMapper integralOrderMapper;
    @Autowired
    IntegralProductMapper integralProductMapper;
    @Autowired
    UserMapper userMapper;
    @Autowired
    private IntegralMapper integralMapper;

    /**
     * 获取全部订单
     * @return
     */
    @ResponseBody
    @RequestMapping("/list")
    public JsonResponse list(HttpServletRequest request){
        try {
            Page page = PageHeper.pageRequest(request);
            Map<String, Object> map = ApplicationUtils.getRequestDatas();
            // IPage iPage = integralOrderMapper.selectPage(page,new QueryWrapper<IntegralOrder>().orderByDesc("create_time")); // 按创建时间降序查询
            Page<IntegralOrder> orderAll = integralOrderMapper.findOrderAll(page, map);

            DataGrid list = DataGrid.gridBuilder(orderAll);
            return JsonResponse.success(list);
        } catch (Exception e){
            e.printStackTrace();
            log.error(e.getMessage());
        }
        return JsonResponse.error(CodeEnum.EX999);
    }

    /**
     * 订单发货
     * @param params
     * @param id
     * @return
     */
    @ResponseBody
    @RequestMapping("/modify")
    public JsonResponse modify(@RequestParam Map<String,Object> params,String id){
        try {
            IntegralOrder old = integralOrderMapper.selectById(id);
            IntegralOrder newBean = JSON.parseObject(JSON.toJSONString(params), IntegralOrder.class);
            BeanUtils.copyProperties(newBean,old,"id","createTime");
            old.setState(0); // 状态改为已发货
            integralOrderMapper.updateById(old);
            return JsonResponse.success(CodeEnum.EX0);
        } catch (Exception e){
        e.printStackTrace();
        log.error(e.getMessage());
    }
        return JsonResponse.error(CodeEnum.EX999);
    }


    /**
     * 创建订单
     * @param params
     * @return
     */
    @Transactional
    @ResponseBody
    @RequestMapping("/add")
    public JsonResponse add(@RequestParam Map<String,Object> params,HttpServletRequest request,String productId){
        try {
            IntegralProduct product = integralProductMapper.selectById(productId);
            if(product.getState() != 0){
                return JsonResponse.error("产品状态无效");
            }
            if(product.getStock() <= 0){
                return JsonResponse.error("产品库存不足");
            }
            if (!integralCount(product)){
                return JsonResponse.error("用户积分不足");
            }
            Date newDate = new Date();
            if (newDate.getTime() < product.getStartTime().getTime() || newDate.getTime() > product.getEndTime().getTime()){
                return JsonResponse.error("不在活动有效期内");
            }
            User user = ApplicationUtils.getUser().getUser();
            IntegralOrder integralOrder = JSON.parseObject(JSON.toJSONString(params), IntegralOrder.class);
            integralOrder.setIntegral(product.getIntegral());
            integralOrder.setProductName(product.getProductName());
            integralOrder.setState(1); // 0:已发货 1:待发货
            integralOrder.setType(product.getType());
            integralOrder.setCreaterId(user.getId());
            integralOrder.setOrderNumber(new SimpleDateFormat("yyyyMMddHHmmssSSS" ).format(new Date()));
            integralOrderMapper.insert(integralOrder); // 创建订单

            product.setStock(product.getStock() - 1);
            integralProductMapper.updateById(product); // 修改产品库存

            Integral integral = new Integral();  // 创建消费记录
            integral.setUserId(user.getId());
            integral.setIntegral(- product.getIntegral());
            integral.setNickName(user.getNickName());
            integral.setType(4);
            integral.setRemark("兑换产品： "+product.getProductName() + ", 手机号码： "+ user.getMobile());
            integralMapper.insert(integral);

            return JsonResponse.success(CodeEnum.EX0);
        } catch (Exception e){
            e.printStackTrace();
            log.error(e.getMessage());
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
        }
        return JsonResponse.error(CodeEnum.EX999);
    }


    /**
     * // 扣除个人积分
     * @param product
     * @return
     */
    private boolean integralCount(IntegralProduct product){
        User user = ApplicationUtils.getUser().getUser();
        if (user.getIntegral() >= product.getIntegral()){
            user.setIntegral(user.getIntegral() - product.getIntegral());
            userMapper.updateById(user);
            return true;
        } else {
            return false;
        }
    }


}